package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TimelineService timelineService;

    @Override
    public String publish(Movement movement) {
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement);
        timelineService.saveTimeline(movement);
        return movement.getId().toHexString();
    }

    @Override
    public PageResult<Movement> findPageByUserId(Long userId, Integer page, Integer pageSize) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Movement.class);
        query.skip((page - 1) * pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult<>(page, pageSize, (int) count, movements);
    }

    @Override
    public List<Movement> findFriendMovements(Long userId, Integer page, Integer pageSize) {
        Query query = new Query(Criteria.where("friendId").is(userId))
                .skip((page - 1) * pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);
        List<ObjectId> movementId = CollUtil.getFieldValues(timeLines, "movementId", ObjectId.class);
        query = new Query(Criteria.where("id").in(movementId)).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    @Override
    public List<Movement> randamMovements(Integer pagesize) {
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(pagesize));
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        return results.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));
        return mongoTemplate.find(query, Movement.class);
    }

    @Override
    public Movement findById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Movement.class);
    }

    @Override
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        Query query = Query.query(Criteria.where("userId").is(uid));
        if(state != null){
            query.addCriteria(Criteria.where("state").is(state));
        }

        long count = mongoTemplate.count(query, Movement.class);
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize, (int) count,movementList);
    }

    @Override
    public void updateState(String movementId, int state) {
        mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(new ObjectId(movementId))),
                Update.update("state",state),Movement.class);
    }

}
